package com.ycsj.goldmedalnewconcept.master.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.image.ImageUtil;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PickChooseManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.activity.AboutUsActivity;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;

/**
 * 编辑关于我们
 * Created by Administrator on 2019/2/22 0022.
 */

public class MasterEditAboutUsActivity extends BaseActivity {

    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;
    //内容布局
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.main)
    LinearLayout llMain;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_new_num)
    TextView tvNum;
    @BindView(R.id.et_gw)
    EditText etGw;
    @BindView(R.id.et_yx)
    EditText etYx;
    @BindView(R.id.et_lxfs)
    EditText etLxfs;
    @BindView(R.id.lv_addlogo)
    ImageView lvAddlogo;
    @BindView(R.id.lv_addewm)
    ImageView lvAddewm;

    //记录logo的图片地址和二维码的图片地址
    private String path_logo, path_code;

    //定义logo和二维码跳转的请求码
    public static final int REQUEST_LOGO = 0x110;
    public static final int REQUEST_CODE = 0x120;

    //页面携带的数据
    private String app_content, app_url, app_email, app_phone;

    /**
     * 跳转到当前页面的方法
     *
     * @param context     上下文
     * @param app_content 内容
     * @param app_url     官方网站
     * @param app_email   联系邮箱
     * @param app_phone   联系方式
     */
    public static void goActivity(Context context, String app_content, String app_url, String app_email, String app_phone) {
        Intent it = new Intent(context, MasterEditAboutUsActivity.class);
        it.putExtra("app_content", app_content);
        it.putExtra("app_url", app_url);
        it.putExtra("app_email", app_email);
        it.putExtra("app_phone", app_phone);
        context.startActivity(it);
    }


    @Override
    protected int getContentLayout() {
        return R.layout.activity_master_edit_about_us;
    }

    @Override
    protected void init() {
        //初始化状态栏
        initStateBar();

        //初始化标题栏
        initTitle();

        //获取传递内容
        initIntent();

        //设置输入内容的监听
        initListener();
    }

    /**
     * 获取传递的内容
     */
    private void initIntent() {
        app_content = getIntent().getStringExtra("app_content");

        app_url = getIntent().getStringExtra("app_url");
        app_email = getIntent().getStringExtra("app_email");
        app_phone = getIntent().getStringExtra("app_phone");

        //简介
        if (!TextUtils.isEmpty(app_content)) {
            etContent.setText(app_content.replace("\\n", "\n"));
            LogUtils.iTag("test", app_content);
            LogUtils.iTag("test", app_content.replace("\\n", "\n"));
        }

        //官网
        if (!TextUtils.isEmpty(app_url)) {
            etGw.setText(app_url);
        }

        //邮箱
        if (!TextUtils.isEmpty(app_email)) {
            etYx.setText(app_email);
        }

        //邮箱
        if (!TextUtils.isEmpty(app_phone)) {
            etLxfs.setText(app_phone);
        }
    }

    /**
     * 初始化标题栏
     */
    private void initTitle() {
        tvTitle.setText("编辑关于我们");
        rlLoading.setVisibility(View.GONE);
        lvEdit.setVisibility(View.VISIBLE);
        lvEdit.setScaleType(ImageView.ScaleType.FIT_CENTER);
        //设置保存按钮的长宽
        int width = UiUtils.dp2px(120);
        int height = width / 2;
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width, height);
        lvEdit.setLayoutParams(lp);
        lvEdit.setImageResource(R.drawable.bt_save);
    }

    /**
     * 设置监听
     */
    private void initListener() {
        etContent.setFilters(new InputFilter[]{new MaxTextLengthFilter(501)});

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etContent.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tvNum.setText("0/500");
                } else {
                    if (inputText.length() > 501) {
                        tvNum.setText("500/500");
                    } else {
                        tvNum.setText(inputText.length() + "/500");
                    }
                }
            }
        });
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit, R.id.lv_addlogo, R.id.lv_addewm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:
                //保存
                doSaveAction();
                break;
            case R.id.lv_addlogo:
                //上传logo
                PickChooseManager.startPhotoPickActivity(this, 1, REQUEST_LOGO);
                break;
            case R.id.lv_addewm:
                //上传二维码
                PickChooseManager.startPhotoPickActivity(this, 1, REQUEST_CODE);
                break;
        }
    }

    //上传的Logo和二维码文件
    private File logoFile, qrFile;

    /**
     * 保存的操作
     */
    private void doSaveAction() {
        // 内容介绍
        final String content = etContent.getText().toString().trim();
        // 官方网站
        final String gw = etGw.getText().toString().trim();
        //邮箱
        final String yx = etYx.getText().toString().trim();
        //联系方式
        final String lxfs = etLxfs.getText().toString().trim();

        if (TextUtils.isEmpty(content)) {
            SnackbarUtil.ShortSnackbar(llMain, "请输入介绍文字", 0).show();
            return;
        }

        if (TextUtils.isEmpty(gw)) {
            SnackbarUtil.ShortSnackbar(llMain, "请输入官网地址", 0).show();
            return;
        }

        //验证网站的正确性
//        if (!RegexUtils.isUrlAddress(gw)) {
//            SnackbarUtil.ShortSnackbar(llMain, "不是正确的网址，请注意检查一下", 0).show();
//            return;
//        }

        if (TextUtils.isEmpty(yx)) {
            SnackbarUtil.ShortSnackbar(llMain, "请输入邮箱", 0).show();
            return;
        }

        //验证邮箱的正确性
//        if (!RegexUtils.isEmail(yx)) {
//            SnackbarUtil.ShortSnackbar(llMain, "输入的邮箱格式不对,请检查", 0).show();
//            return;
//        }

        if (TextUtils.isEmpty(lxfs)) {
            SnackbarUtil.ShortSnackbar(llMain, "请输入联系方式", 0).show();
            return;
        }

//        if (!RegexUtils.isTel(lxfs) || !RegexUtils.isMobile(lxfs)) {
//            SnackbarUtil.ShortSnackbar(llMain, "输入的联系方式格式不对,请检查", 0).show();
//            return;
//        }


        //Logo和二维码
//        if (TextUtils.isEmpty(path_logo)) {
//            SnackbarUtil.ShortSnackbar(llMain, "您还未上传Logo", 0).show();
//            return;
//        }

//        if (TextUtils.isEmpty(path_code)) {
//            SnackbarUtil.ShortSnackbar(llMain, "您还未上传二维码", 0).show();
//            return;
//        }

        //判断是否修改页面内容
        if (!hasUpdate()) {
            //没有修改页面信息
            ToastUtils.showShort("未修改任何信息,不需要上传");
            return;
        } else {
            //修改了页面信息
            if (!TextUtils.isEmpty(path_logo) || !TextUtils.isEmpty(path_code)) {

                //有图压缩图片后上传
                List<File> files = new ArrayList<>();

                if (!TextUtils.isEmpty(path_logo)) {
                    logoFile = new File(path_logo);
                }

                if (!TextUtils.isEmpty(path_code)) {
                    qrFile = new File(path_code);
                }

                if (logoFile != null && qrFile != null) {
                    //证明logo和二维码都上传了
                    files.add(logoFile);
                    files.add(qrFile);
                } else if (logoFile != null && qrFile == null) {
                    //只上传了logo
                    files.add(logoFile);
                } else if (logoFile == null && qrFile != null) {
                    //只上传了二维码
                    files.add(qrFile);
                }

                Luban.compress(this, files).setMaxSize(150).setMaxHeight(1280).setMaxWidth(720).putGear(Luban.CUSTOM_GEAR).launch(new OnMultiCompressListener() {

                    @Override
                    public void onStart() {
                        //压缩开始
                    }

                    @Override
                    public void onSuccess(List<File> fileList) {
                        //上传
                        doPostAction(fileList, content, gw, lxfs, yx);
                    }

                    @Override
                    public void onError(Throwable e) {
                        //压缩错误
                    }
                });
            } else {
                //上传
                doPostAction(null, content, gw, lxfs, yx);
            }
        }
    }


    /**
     * 是否修改了页面信息
     *
     * @return
     */
    private boolean hasUpdate() {
        boolean res = false;
        if (!TextUtils.isEmpty(path_logo) || !TextUtils.isEmpty(path_code)) {
            res = true;
        } else {
            // 内容介绍
            final String content = etContent.getText().toString().trim();

            // 官方网站
            final String gw = etGw.getText().toString().trim();
            //邮箱
            final String yx = etYx.getText().toString().trim();
            //联系方式
            final String lxfs = etLxfs.getText().toString().trim();
            if (!content.equals(app_content.replace("\\n", "\n"))) {
                res = true;
            }

            if (!gw.equals(app_url)) {
                res = true;
            }

            if (!yx.equals(app_email)) {
                res = true;
            }
            if (!lxfs.equals(app_phone)) {
                res = true;
            }
        }
        return res;
    }

    /**
     * 上传
     *
     * @param fileList
     * @param content
     * @param gw
     * @param lxfs
     * @param yx
     */
    private void doPostAction(List<File> fileList, String content, String gw, String lxfs, String yx) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("type", "202");
        paramsMap.put("platform", "2");
        paramsMap.put("acc", AccountUtils.getAccount(MasterEditAboutUsActivity.this));
        paramsMap.put("role", AccountUtils.getRole(MasterEditAboutUsActivity.this));
        paramsMap.put("school", AccountUtils.getSchoolId(MasterEditAboutUsActivity.this));
        paramsMap.put("app_content", content);
        paramsMap.put("app_url", gw);
        paramsMap.put("app_phone", lxfs);
        paramsMap.put("app_email", yx);
        paramsMap.put("app_address", "");

        CustomDialogManager.show(MasterEditAboutUsActivity.this, "上传中...");

        PostFormBuilder params = OkHttpUtils.post().url(HttpAddress.UPDATEABOUTUS).params(paramsMap);

        if (null != fileList) {
            //证明上传了图片
            if (logoFile != null && qrFile != null) {
                //证明logo和二维码都上传了
                params.addFile("logo", "logo.jpg", fileList.get(0));
                params.addFile("code", "code.jpg", fileList.get(1));
            } else if (logoFile != null && qrFile == null) {
                //只上传了logo
                params.addFile("logo", "logo.jpg", fileList.get(0));
            } else if (logoFile == null && qrFile != null) {
                //只上传了二维码
                params.addFile("code", "code.jpg", fileList.get(0));
            }
        }

        params.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort("保存异常");
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                ResultInfo info = GsonUtil.jsonToBean(response, ResultInfo.class);
                if ("200".equals(info.getState())) {
                    //上传成功
                    ToastUtils.showShort("保存成功");
                    BusInfo busInfo = new BusInfo();
                    busInfo.type = AboutUsActivity.UPDATE;
                    EventBus.getDefault().post(busInfo);

                    finish();
                } else if ("-1".equals(info.getState())) {
                    ToastUtils.showShort("保存异常");
                } else if ("104".equals(info.getState())) {
                    ToastUtils.showShort("保存失败,没有找到学校");
                }
            }
        });
    }

    /**
     * 请求图库后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_LOGO) {
            //LOGO
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                path_logo = photos.get(0);
                ImageUtil.displayImage(this, lvAddlogo, path_logo);
            }
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            //二维码
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                path_code = photos.get(0);
                ImageUtil.displayImage(this, lvAddewm, path_code);
            }
        }
    }

}
